package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.PageDto;
import com.itheima.ydd.dto.UserDataDto.UserDataListDto;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.exception.ConsumerException;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.AppJwtUtil;
import com.itheima.ydd.utils.TextTransUtil;
import com.sun.deploy.ui.DialogTemplate;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shiqiang
 * @version 1.0
 * @date 2022/4/10 21:22
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddUserDataService yddUserDataService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddUserService yddUserService;

    /**
     * 查看我的文章(带分页)
     * @param limit
     * @param page
     * @return
     */
    @Override
    public PageDto<YddArticle> getMyArticle(String limit, String page,HttpServletRequest request) {
        //获取用户id(用token)
        Integer userId = getUserId(request);
        //查询文章
        //构造分页构造器
        PageDto<YddArticle> iPage=new PageDto<>(Integer.parseInt(page),Integer.parseInt(limit));
        //构造条件构造器
        LambdaQueryWrapper<YddArticle> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(userId),YddArticle::getUserId,userId);
        return yddArticleService.page(iPage, wrapper);
    }

    /**
     * 分页查看我的点赞收藏文章同时带有分类名称
     * @param type
     * @param limit
     * @param page
     */
    @Override
    @Transactional
    public ResponseEntity<Result> getUserDataList(String type, String limit, String page, HttpServletRequest request) {
        //获取用户id
        //Integer userId = getUserId(request);
        int userId=136;
        //根据用户id和type查询文章yddUserData
        PageDto<YddUserData> dataIPage=new PageDto<>(Integer.parseInt(page),Integer.parseInt(limit));
        LambdaQueryWrapper<YddUserData> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(YddUserData::getUserId,userId);
        wrapper.eq(StringUtils.hasText(type),YddUserData::getType,Integer.parseInt(type));
        //分页查询用户点赞,收藏
        PageDto<YddUserData> userDataIPage = yddUserDataService.page(dataIPage, wrapper);
        List<YddUserData> getDataList = userDataIPage.getdata();
        PageDto<YddArticleDto> dtoIPage=new PageDto<>();
        //分页拷贝,忽略records
        BeanUtils.copyProperties(dataIPage,dtoIPage,"records");
        List<YddUserData> dataList = userDataIPage.getdata();
        YddArticleDto articleDto=new YddArticleDto();
        List<YddArticleDto> list=new ArrayList<>();

        for (YddUserData yddUserData : dataList) {
            //获取文章id
            Integer articleId = yddUserData.getArticleId();
            //获取文章数据
            YddArticle article = yddArticleService.getById(articleId);
            System.out.println(123456);
            //文件拷贝
            if(!ObjectUtils.isEmpty(article)){
                BeanUtils.copyProperties(article,articleDto);
                //获取分类id
                Integer cateId = article.getCateid();
                //获取分类对象
                YddCate cate = yddCateService.getById(cateId);
                String cateName = cate.getCatename();
                articleDto.setCatename(cateName);
                list.add(articleDto);
            }
        }

        dtoIPage.setRecords(list);
        List<PageDto<YddArticleDto>> pageDtoList=new ArrayList<>();
        pageDtoList.add(dtoIPage);
        UserDataListDto listDto=new UserDataListDto();
        listDto.setList(dtoIPage);
        return ResponseEntity.ok(new Result(0,"成功",listDto));
    }
    /**
     * 删除我的文章
     * @param id
     */
    @Override
    @Transactional
    public void delArticleById(String id,HttpServletRequest request) {
        //删除yddUserData表中的id关系
        LambdaQueryWrapper<YddUserData> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(id),YddUserData::getArticleId,Integer.parseInt(id));

        yddUserDataService.remove(wrapper);
        //删除文章
        yddArticleService.removeById(Integer.parseInt(id));
    }

    /**
     * 修改我的文章
     * @param article
     */
    @Override
    public void editArticle(YddArticle article,HttpServletRequest request) {
        Integer userId = getUserId(request);
        YddArticle yddArticle = yddArticleService.getById(article.getId());
        if (userId!=yddArticle.getUserId()){
            throw new ConsumerException("不是您的文章,不可以修改");
        }
        LambdaQueryWrapper<YddArticle>  wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(article.getTitle()),YddArticle::getTitle,article.getTitle());
        YddArticle article1 = yddArticleService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(article1)&&!article.getId().equals(article1.getId())){
            throw new ConsumerException("标题已存在");
        }
        yddArticleService.updateById(article);
    }

    /**
     *点赞/取消点赞和收藏/取消收藏
     * @param type
     * @param article_id
     * @param action
     */
    @Override
    public void userDataHandle(String type,String article_id, String action,HttpServletRequest request) {
        //获取用户id
        Integer userId = getUserId(request);
        YddUserData yddUserData=new YddUserData();
        yddUserData.setUserId(userId);
        yddUserData.setArticleId(Integer.parseInt(article_id));
        yddUserData.setType(Integer.parseInt(type));
        if (StringUtils.pathEquals(action,"add")){
            //添加点赞或收藏
            yddUserDataService.save(yddUserData);
        }else{
            //删除点赞或收藏
            LambdaQueryWrapper<YddUserData> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(yddUserData.getArticleId()!=null,YddUserData::getArticleId,yddUserData.getArticleId());
            wrapper.eq(yddUserData.getType()!=null,YddUserData::getType,yddUserData.getType());
            wrapper.eq(yddUserData.getUserId()!=null,YddUserData::getUserId,yddUserData.getUserId());
            yddUserDataService.remove(wrapper);
        }
    }
    /**
     * 修改用户资料
     * @param yddUser
     */
    @Override
    public void update(YddUser yddUser,HttpServletRequest request) {

        LambdaUpdateWrapper<YddUser> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(yddUser.getUsername()!=null,YddUser::getUsername,yddUser.getUsername());
        YddUser user = yddUserService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(user)&&!yddUser.getId().equals(user.getId())){
            throw new ConsumerException("用户名已存在");
        }
        yddUserService.updateById(yddUser);
    }

    /**
     * 发布文章
     * @param article
     */
    @Override
    public void addArticle(YddArticle article,HttpServletRequest request) {
        Integer userId = getUserId(request);
        article.setUserId(userId);
        yddArticleService.save(article);
    }

    @Override
    public YddUser getUserInfo(HttpServletRequest request) {
        Integer userId = getUserId(request);
        return yddUserService.getById(userId);
    }
    //从token中获取用户id
    private Integer getUserId(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //获取用户id
        boolean flag = AppJwtUtil.verifyToken(token);
        if (!flag){
            throw new ConsumerException("token已失效");
        }
        Claims claims = AppJwtUtil.getClaims(token);
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
